package Core

import (
	"bytes"
	"html/template"
	"io/ioutil"
	"path"
)

// declare global template functions
var globalTemplateFuncs template.FuncMap

func init() {
	globalTemplateFuncs = template.FuncMap{
		"Raw":func(str string) template.HTML {
			return template.HTML(str)
		},
	}
}

// Set global template func
func SetTemplateFunc(key string, fn interface {}) {
	globalTemplateFuncs[key] = fn
}

func RenderFiles(tplFiles []string, data map[string]interface {}, fnMap template.FuncMap) string {
	t := template.New(path.Base(tplFiles[0]))
	// append native view func to all
	if fnMap == nil {
		fnMap = make(template.FuncMap)
	}
	for k, v := range globalTemplateFuncs {
		fnMap[k] = v
	}
	t = t.Funcs(fnMap)
	var e error
	t, e = t.ParseFiles(tplFiles...)
	if e != nil {
		panic(e)
	}
	var buffer bytes.Buffer
	e = t.ExecuteTemplate(&buffer, path.Base(tplFiles[0]), data)
	if e != nil {
		panic(e)
	}
	return buffer.String()
}

// Render template file
func RenderFile(tplFile string, data map[string]interface {}, fnMap template.FuncMap) string {
	bytes, e := ioutil.ReadFile(tplFile)
	if e != nil {
		panic(e)
	}
	return Render(path.Base(tplFile), string(bytes), data, fnMap)
}

// Render template string
func Render(name, tplString string, data map[string]interface {}, fnMap template.FuncMap) string {
	t := template.New(name)
	// append native view func to all
	if fnMap == nil {
		fnMap = make(template.FuncMap)
	}
	for k, v := range globalTemplateFuncs {
		fnMap[k] = v
	}
	t = t.Funcs(fnMap)
	var e error
	t, e = t.Parse(tplString)
	if e != nil {
		panic(e)
	}
	var buffer bytes.Buffer
	e = t.Execute(&buffer, data)
	if e != nil {
		panic(e)
	}
	return buffer.String()
}

func ThemeFile(themeName string, file string) string {
	themeName = Config.String("theme." + themeName)
	return path.Join(RootDir, themeName, file)
}

